package com.funsport.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.funsport.entity.Order;
import com.funsport.mapper.OrderMapper;
import com.funsport.service.IOrderService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.Random;

/**
 * 订单服务实现类
 */
@Slf4j
@Service
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public Order createOrder(Long userId, String orderType, Long businessId, BigDecimal amount) {
        // 生成订单号
        String orderNo = generateOrderNo();
        
        Order order = new Order();
        order.setOrderNo(orderNo);
        order.setUserId(userId);
        order.setOrderType(orderType);
        order.setBusinessId(businessId);
        order.setAmount(amount);
        order.setStatus("pending");
        order.setPaymentMethod("wechat");
        
        this.save(order);
        log.info("订单创建成功: {}", orderNo);
        
        return order;
    }
    
    @Override
    public Order getByOrderNo(String orderNo) {
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderNo, orderNo);
        return this.getOne(wrapper);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updatePaidStatus(String orderNo, String transactionId) {
        Order order = getByOrderNo(orderNo);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        order.setStatus("paid");
        order.setTransactionId(transactionId);
        order.setPaidAt(LocalDateTime.now());
        
        this.updateById(order);
        log.info("订单支付成功: {}, 交易号: {}", orderNo, transactionId);
    }
    
    @Override
    @Transactional(rollbackFor = Exception.class)
    public void updateRefundStatus(String orderNo, BigDecimal refundAmount, String refundReason) {
        Order order = getByOrderNo(orderNo);
        if (order == null) {
            throw new RuntimeException("订单不存在");
        }
        
        order.setStatus("refunded");
        order.setRefundAmount(refundAmount);
        order.setRefundedAt(LocalDateTime.now());
        order.setRefundReason(refundReason);
        
        this.updateById(order);
        log.info("订单退款成功: {}, 退款金额: {}", orderNo, refundAmount);
    }
    
    /**
     * 生成订单号
     */
    private String generateOrderNo() {
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMddHHmmss");
        String timestamp = LocalDateTime.now().format(formatter);
        String random = String.format("%06d", new Random().nextInt(1000000));
        return "ORD" + timestamp + random;
    }
}

